package com.ygqh.baby.service.linkstars.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ygqh.baby.ao.OrderStatus;
import com.ygqh.baby.mapper.YgLinkStarsMapper;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgOrderDetail;
import com.ygqh.baby.service.linkstars.YgLinkStarsService;
import com.ygqh.baby.service.linkstars.model.Goods;
import com.ygqh.baby.service.linkstars.model.LSResult;
import com.ygqh.baby.service.linkstars.model.Order;
import com.ygqh.baby.service.wechat.util.MD5;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.HttpUtil;

@Service
public class YgLinkStarsServiceImpl implements YgLinkStarsService {
	protected final Logger logger = Logger.getLogger(this.getClass());

	private static final String apiKey = "3e0f10aeb9d7409437db63a252510569";
	private static final String orderPushUrl = "https://www.linkstars.com/api/adv/cps/order";
	private static final String effectPushUrl = "https://www.linkstars.com/api/adv/cps/effect";

	@Autowired
	private YgLinkStarsMapper ygLinkStarsMapper;

	@SuppressWarnings("deprecation")
	private String getLSKey(String jsonString) {
		String s = apiKey + jsonString;
		URLEncoder.encode(s);
		/**
		 * 生成方式为：“广告主 API 秘钥（api_key）”连接“order 数组经 过 JSON ENCODE 后字符串”，然后做 MD5
		 * 散列运算，最后将 MD5 串中的字母全部转为小写即得到 key 的值。 以伪代码举例：key = lowercase (md5
		 * (strcat (api_key, jsonencode(order_array))))
		 */

		return MD5.MD5Encode(s).toLowerCase();
	}

	@Override
	public LSResult orderPush(YgOrder ygOrder) {
		List<Goods> goodsList = new ArrayList<Goods>();
		BigDecimal rate = new BigDecimal("0.15");
		// 剩余金额
		BigDecimal surplusAmount = ygOrder.getTotalPrice();
		List<YgOrderDetail> orderDetail = ygOrder.getOrderDetail();
		BigDecimal orderCommission = new BigDecimal(0);
		if (ygOrder.getTotalPrice().compareTo(new BigDecimal("0.00")) == 0) {
			return new LSResult(-1, "零元订单", null);
		}
		for (int i = 0; i < orderDetail.size(); i++) {
			YgOrderDetail detail = orderDetail.get(i);
			/**
			 * 例如：A 商品 50 元、B 商品 30 元，订单总额 80 元，优惠券支付 10 元，实际支付 70 元。则： A
			 * 商品真实单价为 50*(70/80) = 43.75 B 商品真实单价为 30*(70/80) = 26.25
			 */
			BigDecimal salePrice = detail.getSalePrice();
			Goods goods = null;
			BigDecimal price = null;

			if (i == orderDetail.size() - 1) {
				price = surplusAmount.divide(new BigDecimal(detail.getQuantity()), BigDecimal.ROUND_HALF_UP);
			} else {
				price = salePrice.multiply((ygOrder.getTotalPrice().divide(ygOrder.getProductPrice(), BigDecimal.ROUND_HALF_UP))).setScale(2,
						BigDecimal.ROUND_HALF_UP);
				surplusAmount = surplusAmount.subtract(price.multiply(new BigDecimal(detail.getQuantity())));
			}

			BigDecimal goodCommission = price.multiply(new BigDecimal(detail.getQuantity())).multiply(rate).setScale(2, BigDecimal.ROUND_HALF_UP);
			goods = new Goods(detail.getSkuId(), detail.getProductName(), price, 1, rate, detail.getQuantity().intValue(), goodCommission);
			orderCommission = orderCommission.add(goodCommission);
			goodsList.add(goods);
		}
		String feedback = ygOrder.getSourceCode().substring(ygOrder.getSourceCode().indexOf("_") + 1);
		String formatDate = DateConvertUtils.format(ygOrder.getCreateTime(), DateConvertUtils.DATE_FORMAT_1, Locale.ENGLISH);
		Order order = new Order(feedback, ygOrder.getOrderId().toString(), formatDate, ygOrder.getTotalPrice(), ygOrder.getOrderStatus().getCode(),
				orderCommission, goodsList);

		String str = JSON.toJSONString(order);
		logger.info(str);
		String key = this.getLSKey(str);
		String param = "key=" + key + "&order=" + URLEncoder.encode(str);
		LSResult result = null;
		try {
			String post = HttpUtil.con_post(orderPushUrl, param);
			JSONObject jsonObject = JSON.parseObject(post);
			result = JSON.toJavaObject(jsonObject, LSResult.class);
		} catch (IOException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public LSResult effectPush(List<YgOrder> ygOrderList) {
		List<Order> oList = new ArrayList<Order>();
		for (YgOrder ygOrder : ygOrderList) {
			String feedback = ygOrder.getSourceCode().substring(ygOrder.getSourceCode().indexOf("_") + 1);
			Order order = new Order(feedback, ygOrder.getOrderId().toString(), ygOrder.getOrderStatus().getCode());
			oList.add(order);
		}
		String jsonString = JSON.toJSONString(oList);
		logger.info(jsonString);
		String lsKey = getLSKey(jsonString);
		String param = "key=" + lsKey + "&order=" + jsonString;
		LSResult result = null;
		try {
			String con_post = HttpUtil.con_post(effectPushUrl, param);
			// result = JSON.toJavaObject(jsonObject, LSResult.class);
			result = JSONObject.parseObject(con_post, LSResult.class);
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		return result;
	}

	@Override
	public List<YgOrder> getLSOrderByTime(Date startTime, Date endTime, OrderStatus orderStatus, String sign) {
		return ygLinkStarsMapper.getLSOrderByTime(startTime, endTime, orderStatus.name(), sign);

	}

}
